<template>
  <div>
    <div>
      名称：
      <el-input
        size="mini"
        class="cate_sel"
        placeholder="请输入分类名称"
        v-model="classificationName"
        @keyup.enter.native="serachCategory"
      ></el-input>
      <el-button type="primary" size="mini" @click="serachCategory"
        >查询
      </el-button>
    </div>

    <div class="tab_cont" style="max-height: 400px; overflow-y: auto">
      <div class="search_list">
        <ul>
          <li v-for="(item, index) in searchList" :key="index">
            <el-radio
              v-model="searchRaido"
              :label="index"
              @change="searchChange"
              ><span></span
            >
              {{ item.categoryPath }}>{{ item.classificationName }}
                | <el-tag size="mini">税率：{{ item.taxRate }}</el-tag>
                | <el-tag size="mini">税类编码：{{ item.taxCateNo }}</el-tag>
                | <el-tag size="mini">税类名称：{{ item.taxCateName }}</el-tag>
            </el-radio>
          </li>
        </ul>
      </div>
      <el-tree
        ref="tree"
        :data="treeData"
        show-checkbox
        :load="loadNode"
        lazy
        accordion
        node-key="categoryUuid"
        :props="defaultProps"
        :render-content="renderContent"
        @check="handleCheckChange"
        @node-click="handleNodeClick"
      >
      </el-tree>
    </div>
    <div style="text-align: right">
      <el-button type="primary" @click="submitFn">确定</el-button>
      <el-button @click="cancelFn">取消</el-button>
    </div>
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
export default {
  name: 'categorySelect',
  props: {
    notQueryClassify: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      apiObj: {
        // 查询一级分类
        getLevelOneCategoryList: {
          url: '/sysback/product/collect/getLevelOneCategoryList',
          type: 'post'
        },
        // 根据父分类查询子分类
        getByParentUuid: {
          url: '/sysback/product/collect/getByParentUuid',
          type: 'post'
        },
        getCaUnderCategory: {
          url: '/sysback/product/collect/getCaUnderCategory',
          type: 'post'
        },
        getCategoryListByKey: {
          url: '/sysback/product/collect/getCategoryListByKey',
          type: 'post'
        },
        getCategoryClassListByKey: {
          url: '/sysback/product/collect/getCategoryClassListByKey',
          type: 'post'
        }
      },
      treeClickCount: 0,
      treeData: [],
      defaultTreeData: [],
      defaultProps: {
        children: 'children',
        label: 'categoryName',
        disabled: 'disabled',
        isLeaf: 'leaf'
      },
      checkedOj: null,
      classificationName: '',
      taxRate: '',
      searchList: [],
      searchRaido: -1
    };
  },
  mounted () {
    this.getLevelOneCategoryList();
  },
  methods: {
    submitFn () {
      let cateVal = null;
      if (this.checkedOj) {
        let curClassId = this.checkedOj.categoryUuid.split('_')[1];
        const nameKey = this.notQueryClassify ? 'categoryName' : 'subName';
        const uuidKey = this.notQueryClassify ? 'categoryUuid' : 'subUuid';
        const classificationName = this.notQueryClassify ? this.checkedOj.classificationName : this.checkedOj.categoryName
        const classificationUuid = this.notQueryClassify ? this.checkedOj.classificationUuid : curClassId
        cateVal = {
          ...this.checkedOj,
          categoryName: this.checkedOj[nameKey],
          categoryUuid: this.checkedOj[uuidKey],
          categoryNo: this.checkedOj?.categoryNo,
          taxRate: this.checkedOj.taxRate,
          classificationName,
          classificationUuid
        };
      }
      if (this.searchRaido != -1) {
        let curChose = this.searchList[this.searchRaido];
        let cateL = curChose.categoryPath.split('>');
        cateVal = {
          ...curChose,
          categoryName: cateL[3],
          categoryUuid: curChose.categoryUuid,
          categoryNo: curChose?.categoryNo,
          classificationName: curChose.classificationName,
          taxRate: curChose.taxRate,
          classificationUuid: curChose.classificationUuid
        };
      }

      if (cateVal) {
        console.log(cateVal);
        this.$emit('submitConcat', cateVal);
        this.$nextTick(() => {
          this.checkedOj = null;
          this.searchRaido = -1;
          this.$refs.tree.setCheckedKeys([]);
          this.treeData = JSON.parse(JSON.stringify(this.defaultTreeData));
        });
      } else {
        this.$message({
          type: 'error',
          message: '请选择分类！'
        });
      }
    },
    cancelFn () {
      this.checkedOj = null;
      this.searchRaido = -1;
      this.$refs.tree.setCheckedKeys([]);
      this.treeData = JSON.parse(JSON.stringify(this.defaultTreeData));
      this.$emit('cancelConcat');
    },
    getLevelOneCategoryList () {
      // 开始请求列表
      ApiRequest(
        this.apiObj.getLevelOneCategoryList.url,
        this.apiObj.getLevelOneCategoryList.type,
        {},
        true
      ).then((res) => {
        if (res.retStatus === '1') {
          this.treeData = this.creatNoChooseNOde(res.retData);
          this.defaultTreeData = this.creatNoChooseNOde(res.retData);
        }
      });
    },
    loadNode (node, resolve) {
      if (node.level === 0) return;
      if (node.level < 4) {
        this.getSubCategory(node.data.categoryUuid, resolve, node.level);
      }

      if (node.level === 4) {
        this.getCaUnderCategory(
          node.data.categoryUuid,
          resolve,
          node.level,
          node.data.categoryName,
          node.data
        );
      }
    },
    // 获取分类路径全名称
    getSubCategory (levelId, resolve, level) {
      let data = { parentUuid: levelId };
      ApiRequest(
        this.apiObj.getByParentUuid.url,
        this.apiObj.getByParentUuid.type,
        data,
        true
      ).then((res) => {
        if (res.retStatus === '1') {
          resolve(this.creatNoChooseNOde(res.retData, level));
        }
      });
    },
    // 查询末及品类的归类名称
    getCaUnderCategory (uuid, resolve, level, parName, cateData) {
      let data = { categoryUuid: uuid };
      ApiRequest(
        this.apiObj.getCaUnderCategory.url,
        this.apiObj.getCaUnderCategory.type,
        data,
        true
      ).then((res) => {
        if (res.retStatus === '1') {
          let treeDt = res.retData.map((item, index) => {
            return {
              ...cateData, // 补全末级品类信息
              categoryName: item.classificationName,
              taxRate: item.taxRate,
              taxCateNo: item.taxCateNo,
              taxCateName: item.taxCateName,
              categoryUuid: uuid + '_' + item.classificationUuid,
              levelNum: 5,
              disabled: false,
              leaf: true,
              subName: parName,
              subUuid: uuid,
            };
          });
          resolve(treeDt);
        }
      });
    },
    serachCategory () {
      if (!this.classificationName.length) return;
      let data = {
        key: this.classificationName
      };

      ApiRequest(
        this.apiObj.getCategoryClassListByKey.url,
        this.apiObj.getCategoryClassListByKey.type,
        data,
        true
      ).then((res) => {
        if (res.retStatus === '1') {
          this.searchList = res.retData;
        }
      });
    },
    searchChange () {
      this.checkedOj = null;
      this.$refs.tree.setCheckedKeys([]);
    },
    creatNoChooseNOde (retData, level) {
      let newData = retData.map((item, index) => {
        if (this.notQueryClassify) {
          const endLevel = 3;
          Object.assign(item, { disabled: (level ?? 0) < endLevel, leaf: level && level == endLevel });
        } else {
          Object.assign(item, { disabled: true, leaf: level && level == 5 });
        }
        return item;
      });
      return newData;
    },
    handleCheckChange (data, checked, node) {
      if (this.checkedOj && data.categoryUuid == this.checkedOj.categoryUuid) {
        this.$refs.tree.setCheckedKeys([]);
        this.checkedOj = null;
      } else {
        this.$refs.tree.setCheckedKeys([data.categoryUuid]);
        this.checkedOj = data;
      }
    },
    // 树形节点双击事件处理
    handleNodeClick (data, node) {
      if (!data.subUuid) {
        return;
      }
      // 记录点击次数
      this.treeClickCount++;
      // 单次点击次数超过2次不作处理,直接返回,也可以拓展成多击事件
      if (this.treeClickCount >= 2) {
        return;
      }
      // 计时器,计算300毫秒为单位,可自行修改
      this.timer = window.setTimeout(() => {
        if (this.treeClickCount == 1) {
          // 把次数归零
          this.treeClickCount = 0;
          // 单击事件处理
        } else if (this.treeClickCount > 1) {
          // 把次数归零
          this.treeClickCount = 0;
          // 双击事件
          let cateVal = null;
          if (data) {
            let curClassId = data.categoryUuid.split('_')[1];
            cateVal = {
              categoryName: data.subName,
              categoryUuid: data.subUuid,
              classificationName: data.categoryName,
              taxRate: data.taxRate,
              classificationUuid: curClassId,
              ...data
            };
          }
          this.$emit('submitConcat', cateVal);
          this.$nextTick(() => {
            this.checkedOj = null;
            this.searchRaido = -1;
            this.$refs.tree.setCheckedKeys([]);
            this.treeData = JSON.parse(JSON.stringify(this.defaultTreeData));
          });
        }
      }, 300);
    },
    renderContent (h, { data }) {
      const renderTag = (label, value) => <el-tag type="info" size="mini">{ `${ label }：${value ?? ''}` }</el-tag>
      const {
        categoryName = '',
        categoryNo = '',
        taxRate = '',
        taxCateNo = '',
        taxCateName = ''
      } = data;
      return <div class="tree-item-wrap">
        <span>{ categoryName }</span>
        <span>{ categoryNo }</span>
        <span>{ taxRate ? renderTag('税率', taxRate) : '' }</span>
        <span>{ taxCateNo ? renderTag('税类编码', taxCateNo) : '' }</span>
        <span>{ taxCateName ? renderTag('税类名称', taxCateName) : '' }</span>
      </div>
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .tree-item-wrap {
  display: flex;
  span:not(:first-child) {
    margin-left: 10px;
  }
}
.cate_sel {
  width: 200px;
  margin-right: 20px;
}

.tab_cont {
  margin: 20px 0;
}

.search_list ul {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 20px;
  margin-bottom: 20px;
}

.search_list ul li {
  line-height: 24px;
}
</style>
